package top.fangw.tenant.runner;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import top.fangw.tenant.pojo.entity.SourceDatabaseInfo;
import top.fangw.tenant.service.ISourceDatabaseInfoService;
import top.fangw.common.mybatis.annotation.DyDataSource;
import top.fangw.common.mybatis.util.DynamicDataSourceUtil;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description: 初始化动态数据源
 * @author: fgw
 * @createDate: 2024/1/19
 */
@Slf4j
@Order(value = 1) // 数字越小，越先执行
@Component
@RequiredArgsConstructor
public class InitDataSource implements CommandLineRunner {
    private final ISourceDatabaseInfoService sourceDatabaseInfoService;

    private final DynamicDataSourceUtil dynamicDataSourceUtil;

    @Override
    @DyDataSource
    public void run(String... args) throws Exception {
        List<SourceDatabaseInfo> list = sourceDatabaseInfoService.list();
        AtomicInteger i = new AtomicInteger(1);
        if (list != null && list.size() > 0) {
            list.forEach(item -> {
                log.info("开始初始化动态数据源：{}/{}", i, list.size());
                DataSourceProperty dataSourceProperty = BeanUtil.copyProperties(item, DataSourceProperty.class);
                dataSourceProperty.setPoolName(item.getDatasourceName());
                dynamicDataSourceUtil.addDataSource(dataSourceProperty);
                i.getAndIncrement();
            });
        }
        log.info("初始化动态数据源完成");
    }
}
